package com.lujianfei.redpacketstat.ui.viewmodel

import android.content.Intent
import android.os.Build
import android.view.View
import androidx.annotation.RequiresApi
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.lujianfei.redpacketstat.App
import com.lujianfei.redpacketstat.Constant
import com.lujianfei.redpacketstat.base.BaseViewModel
import com.lujianfei.redpacketstat.database.AppDatabase
import com.lujianfei.redpacketstat.database.bean.UserEntity
import com.lujianfei.redpacketstat.manager.MessageManager
import com.lujianfei.redpacketstat.manager.NotifyListener
import com.lujianfei.redpacketstat.ui.UserDetailActivity
import com.lujianfei.redpacketstat.utils.ClickHelper
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.withContext

class MainViewModel(private val db: AppDatabase) : BaseViewModel() {

    val uiState = MutableLiveData<MainUiStateEntity>()
    var mClickHelper = ClickHelper()

    fun loadData(status: Int): LiveData<MutableList<UserEntity>> {
        return db.userDao().queryAllByStatus(status)
    }

    fun addUser(userName: String) {
        launchOnIO {
            val user = UserEntity()
            user.userName = userName
            db.userDao().insert(user)
            notifyTabUpdate()
        }
    }

    fun clickOnItem(view: View, userEntity: UserEntity) {
        val intent = Intent()
        intent.setClassName(
            App.instance.packageName,
            "com.lujianfei.redpacketstat.ui.UserDetailActivity"
        )
        intent.putExtra(UserDetailActivity.key_user_id, userEntity.id)
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        App.instance.startActivity(intent)
    }

    fun clickOnProcess(view: View, userEntity: UserEntity) {
        emitUi(showDialog = ShowDialog("提示", "确认操作 ？") {
            launchOnIO {
                if (Constant.STATUS_UNPROCESSED == userEntity.status) {
                    userEntity.status = Constant.STATUS_PROCESSED
                } else if (Constant.STATUS_PROCESSED == userEntity.status) {
                    userEntity.status = Constant.STATUS_UNPROCESSED
                }
                db.userDao().update(userEntity)

                notifyTabUpdate()
            }
        })
    }

    fun notifyTabUpdate() {
        launchOnIO {
            MessageManager.instance.notify(
                unHandleCount = AppDatabase.instance.userDao()
                    .queryCountByStatus(Constant.STATUS_UNPROCESSED),
                handleCount = AppDatabase.instance.userDao()
                    .queryCountByStatus(Constant.STATUS_PROCESSED)
            )
        }
    }


    fun getTotalStatics(callback: (String) -> Unit) {
        launchOnUI {
            emitUi(loading = true)
            val str = async(Dispatchers.IO) {
                val stringBuilder = StringBuilder()
                val queryAll = db.userDao().queryAll()
                var unprocessCount = 0.0
                var processCount = 0.0
                var totalCount = 0.0
                var userCount = 0
                val processedUsers = queryAll.filter { Constant.STATUS_PROCESSED == it.status }
                val unprocessedUsers = queryAll.filter { Constant.STATUS_UNPROCESSED == it.status }
                userCount = processedUsers.size + unprocessedUsers.size
                processedUsers.forEach {
                    val redpacket = db.redpacketDao().queryByUserId(it.id)
                    redpacket?.let { redpacketAfterCheck ->
                        processCount = processCount.plus(redpacketAfterCheck.amount)
                    }
                }
                unprocessedUsers.forEach {
                    val redpacket = db.redpacketDao().queryByUserId(it.id)
                    redpacket?.let { redpacketAfterCheck ->
                        unprocessCount = unprocessCount.plus(redpacketAfterCheck.amount)
                    }
                }
                totalCount = processCount + unprocessCount
                stringBuilder.append("未处理红包：$unprocessCount 元\r\n")
                stringBuilder.append("已处理红包：$processCount 元\r\n")
                stringBuilder.append("\r\n")
                stringBuilder.append("红包总数：$totalCount 元\r\n")
                stringBuilder.append("红包人数：$userCount 位\r\n")
                stringBuilder
            }
            emitUi(loading = false)
            callback(str.await().toString())
        }
    }

    fun emitUi(
        loading: Boolean = false,
        showToast: String? = null,
        refreshUI: Boolean = false,
        showDialog: ShowDialog? = null
    ) {
        uiState.value = MainUiStateEntity(loading, showToast, refreshUI, showDialog)
    }

    fun amountVisibility(): Int {
        return if (App.instance.adminMode) View.VISIBLE else View.GONE
    }

    fun toolBarClick() {
        mClickHelper.clickTimes(maxFastClickTime = 10, duration = 500) {
            App.instance.adminMode = !App.instance.adminMode
            if (App.instance.adminMode) {
                emitUi(showToast = "解锁秘密!", refreshUI = true)
            } else {
                emitUi(showToast = "已隐藏秘密!", refreshUI = true)
            }
        }
    }

    fun appendAmount(userListAfterCheck: MutableList<UserEntity>, finish: () -> Unit = {}) {
        launchOnUI {
            withContext(Dispatchers.IO) {
                userListAfterCheck.forEach { userEntity ->
                    val redPacketEntity =
                        AppDatabase.instance.redpacketDao().queryByUserId(userEntity.id)
                    redPacketEntity?.let { redPacketEntityAfterCheck ->
                        userEntity.amount = redPacketEntityAfterCheck.amount
                    }
                }
            }
            finish()
        }
    }
}

data class MainUiStateEntity(
    val loading: Boolean = false,
    val showToast: String? = null,
    val refreshUI: Boolean = false,
    val showDialog: ShowDialog? = null
)

data class ShowDialog(
    val title: String = "",
    val message: String = "",
    val callback: (confirm: Boolean) -> Unit
)
